package net.wicp.tams.common.thread.rejected;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.apiext.ReflectAssist;

/****
 * 当线程被拒绝时采取的策略，如果线程实现cn.rjzjh.commons.util.thread.ICancelHandle接口则调用
 * 
 * @author andy.zhou
 * 
 */
@Slf4j
public class RejectedExecutionForLog implements RejectedExecutionHandler {
	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		log.error("线程池拒绝，" + "TaskCount:" + executor.getTaskCount() + " ActiveCount:" + executor.getActiveCount()
				+ " CorePoolSize:" + executor.getCorePoolSize());

		if (!executor.isShutdown()) {
			if (ReflectAssist.isInterface(r.getClass(), "net.wicp.tams.common.thread.rejected.ICancelHandle")) {
				ICancelHandle cancelDo = (ICancelHandle) r;
				cancelDo.doCancle();
			} else {//阻塞线程
				try {
					executor.getQueue().put(r);
				} catch (InterruptedException e) {
					log.error("线程池阻塞任务时失败", e);
				}
			}
		}
	}

}
